package ssov5

import (
	"fmt"

	"github.com/micro-plat/hydra"
	"github.com/micro-plat/hydra/conf/server/auth"
	"github.com/micro-plat/hydra/services"
)

var cacheServices []string = make([]string, 0, 5)

//Bind 将SSO服务注册到应用服务器
func Bind(registry services.IMicroRegistry, ssoAPIHost, ident, secret, servicePrefix string) error {

	Unbind()
	if err := bindConf(ssoAPIHost, ident, secret); err != nil {
		return err
	}
	registryNow(registry, servicePrefix, "/member/login", userLogin)
	registryNow(registry, servicePrefix, "/member/logout", userLogout)
	registryNow(registry, servicePrefix, "/menu/list/get", userMenus)
	registryNow(registry, servicePrefix, "/system/info/get", systemInfo)
	registryNow(registry, servicePrefix, "/user/info/get", getUserInfo)
	return nil
}

//Unbind 解除服务绑定
func Unbind() {
	for _, s := range cacheServices {
		hydra.S.Remove(s)
	}
}

//registryNow 注册并缓存服务
func registryNow(registry services.IMicroRegistry, servicePrefix string, service string, handler interface{}) {
	name := fmt.Sprintf("/%s/%s", servicePrefix, service)
	registry(service, handler)
	cacheServices = append(cacheServices, name)
}

func init() {
	auth.AppendExcludes("/*/system/info/get")
	auth.AppendExcludes("/*/member/*")
	auth.AppendExcludes("/*/login/*")
}
